package com.leoren.run.activity.share;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.leoren.run.R;
import com.leoren.run.common.Const;
import com.leoren.run.common.ServerResponse;
import com.leoren.run.common.UrlConstants;
import com.leoren.run.dbbean.UserDB;
import com.leoren.run.log.L;
import com.leoren.run.utils.GsonUtil;
import com.leoren.run.utils.Http.OkHttp.CommonOkHttpClient;
import com.leoren.run.utils.Http.OkHttp.exception.OkHttpException;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataHandle;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataListener;
import com.leoren.run.utils.ToastUtil;
import com.leoren.run.vo.User;

import org.apache.commons.lang3.StringUtils;
import org.litepal.LitePal;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发布社区分享界面
 */
public class PublishCommentActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView backImg;
    private TextView publishBtn;
    private EditText contentEdit;
    private ImageView picImg;
    private String path;

    private int SELECT_PHOTO_IMAGE = 11;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_comment);
        initLayout();
    }

    private void initLayout(){
        backImg = findViewById(R.id.back_btn);
        publishBtn = findViewById(R.id.publish_btn);
        contentEdit = findViewById(R.id.publish_content);
        picImg = findViewById(R.id.publish_img);

        publishBtn.setOnClickListener(this);

        picImg.setOnClickListener(this);
    }

    /**
     * 发布评论
     */
    private void publishComment(){
        String content = contentEdit.getText().toString().trim();
        UserDB userDB = LitePal.findFirst(UserDB.class);
        if (StringUtils.isBlank(content)) {
            ToastUtil.MakeToast("发布内容不能为空");
            return;
        }
        if(userDB == null){
            ToastUtil.MakeToast("请登录后重试");
        }
        L.e("path = ====" + path);
        File file = new File(path);
        if(!file.exists()){
            ToastUtil.MakeToast("发布图片不能为空");
            return;
        }
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("upload_file", file.getName(), fileBody)
                .addFormDataPart("userId", String.valueOf(userDB.getTagId()))
                .addFormDataPart("content", content)
                .build();
        showProgressDialog(this);
        CommonOkHttpClient.uploadFile1(file, requestBody, UrlConstants.PUBLISH_COMMENT, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(String responseStr) {
                closeProgressDialog();
                ServerResponse response = GsonUtil.formatJsonToServerResponse(responseStr);
                if(response.isSuccess()){
                    ToastUtil.MakeToast("成功发送");
                    PublishCommentActivity.this.finish();
                }
            }

            @Override
            public void onFailure(OkHttpException e) {
                closeProgressDialog();
                ToastUtil.MakeToast(e.getMsg() + "====================");
            }
        }));
    }

    /**
     * 选择手机存储图片
     */
    private void selectPhoto(){
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, SELECT_PHOTO_IMAGE);
    }

    /**
     * 回调图片选择
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 11:
                if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                    try {
                        Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        path = cursor.getString(columnIndex);  //获取照片路径
                        Log.e("Find",path + "=================");
                        cursor.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        picImg.setImageBitmap(bitmap);
                    } catch (Exception e) {
                        // TODO Auto-generatedcatch block
                        e.printStackTrace();
                    }
                }
                break;

        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.publish_btn:
                publishComment();
                break;
            case R.id.publish_img:
                selectPhoto();
                break;
            default:
                break;
        }
    }

    public void showProgressDialog(Context context){
        if(progressDialog == null){
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage("正在上传...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    public  void closeProgressDialog(){
        if(progressDialog != null){
            progressDialog.dismiss();
        }
    }
}
